<template>
  <div class="forgotPassword-background-container">
    <DynamicBackground />
    <div class="forgotPassword-container">
      <div class="forgotPassword-form">
        <img src="/public/img/logo.png" alt="Logo" class="logo">
        
        <!-- 只在选择邮箱验证或密保验证时显示按钮 -->
        <button v-if="!showPasswordReset && !showEmailChecking" type="button" class="back-to-login-btn" @click="goToLogin">回到登录页面</button>

        <h2>修改密码</h2>
        <form @submit.prevent="handleSubmit">
          <!-- 显示邮箱验证或密保验证 -->
          <div v-if="!showPasswordReset && !showEmailChecking" class="button-group">
            <button type="button" class="btn" @click="showEmailChecking = 'email'">邮箱验证</button>
            <button type="button" class="btn" @click="showEmailChecking = 'security'">密保验证</button>
          </div>

          <!-- 邮箱验证内容 -->
          <div v-else-if="showEmailChecking === 'email' && !showPasswordReset">
            <h3>邮箱验证</h3>
            <input class="emailCode" type="text" id="emailCode" v-model="emailCode" required placeholder="请输入你的邮箱">
            <div class="emailCode-container">
              <input class="checkingCode" type="text" placeholder="请输入验证码" v-model="checkingCode">
              <button type="button" @click="sendEmailCode">获取验证码</button>
            </div>
            <button class="checking" type="submit">验证</button>
            <button type="button" class="back-btn" @click="showEmailChecking = null">返回</button>
          </div>

          <!-- 密保验证内容 -->
          <div v-else-if="showEmailChecking === 'security' && !showPasswordReset">
            <h3>密保验证</h3>
            <div class="emailCode-container">
              <input class="checkingCode" type="text" placeholder="请输入你的用户名" v-model="checkingUserName">
              <button type="button" @click="getPasswordSecurity">获取密保</button>
            </div>
            <!-- 展示随机选择的密保问题 -->
            <div v-if="securityQuestion">
              <p>密保问题: {{ securityQuestion }}</p>
              <input class="checkingCode" type="text" placeholder="请输入密保答案" v-model="userAnswer">
              <button class="checking" type="submit" @click="checkPasswordSecurity">验证密保</button>
            </div>
            <button type="button" class="back-btn" @click="showEmailChecking = null">返回</button>
          </div>
          
          <!-- 密码重置内容 -->
          <div v-else-if="showPasswordReset">
            <h3>重置密码</h3>
            <input type="password" v-model="newPassword" placeholder="新密码" required>
            <input type="password" v-model="confirmPassword" placeholder="确认新密码" required>
            <button class="checking" type="submit">提交</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import DynamicBackground from '../components/DynamicBackground.vue';
import { useRouter } from 'vue-router';
import "../css/forgotPassword.css"
const router = useRouter();

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const showEmailChecking = ref(null);
const showPasswordReset = ref(false);
const emailCode = ref('');
const checkingCode = ref('');
const systemCode = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const checkingUserName = ref('');
const securityQuestion = ref('');
const securityAnswer = ref('');
const userAnswer = ref('');

const sendEmailCodeLink = "http://localhost:8080/user/sendEmailCode";
const forgotPasswordLink = "http://localhost:8080/user/forgotPassword";
const getPasswordSecurityLink = "http://localhost:8080/user/getPasswordSecurity";

const goToLogin = () => {
  router.push({ name: 'Login' });
};

const handleSubmit = async () => {
  if (showPasswordReset.value) {
    if (newPassword.value === confirmPassword.value) {
      const changePasswordDto = {
        email: emailCode.value,
        newPassword: newPassword.value
      };
      const response = await axios.post(forgotPasswordLink, changePasswordDto, {
        headers: { 
          'Content-Type': 'application/json',
        },
      });

      const result = response.data;
      const state = result.state;
      const errMessage = result.errMessage;

      if (state) {
        showPasswordReset.value = false;
        emailCode.value = '';
        checkingCode.value = '';
        newPassword.value = '';
        confirmPassword.value = '';
        alert("密码重置成功，请登录");
        router.push({ name: 'Login' });
      } else {
        alert(errMessage);
      }
    } else {
      alert('新密码和确认密码不匹配！');
    }
  } else if (showEmailChecking.value === 'email' && validateEmail(emailCode.value)) {
    if (checkingCode.value === systemCode.value) {
      showPasswordReset.value = true;
      showEmailChecking.value = null;
    } else {
      alert('验证码不正确！');
    }
  } else {
    alert('请输入有效的邮箱地址');
  }
};

const sendEmailCode = async () => {
  if (validateEmail(emailCode.value)) {
    const response = await axios.post(sendEmailCodeLink, emailCode.value, {
      headers: { 
        'Content-Type': 'application/json',
      },
    });

    const result = response.data;
    const state = result.state;
    const errMessage = result.errMessage;

    if (state) {
      alert("验证码为:" + response.data.data);
      systemCode.value = response.data.data;
    } else {
      alert(errMessage);
    }
  } else {
    alert('请输入有效的邮箱地址');
  }
};

const getPasswordSecurity = async () => {
  try {
    const response = await axios.post(getPasswordSecurityLink, checkingUserName.value, {
      headers: { 
        'Content-Type': 'application/json',
      },
    });

    const result = response.data;
    const state = result.state;
    const errMessage = result.errMessage;

    if (state) {
      const securityQuestions = response.data.data;
      if (securityQuestions.length > 0) {
        const randomQuestion = securityQuestions[Math.floor(Math.random() * securityQuestions.length)];
        securityQuestion.value = randomQuestion.question;
        securityAnswer.value = randomQuestion.answer;
      } else {
        alert('未找到密保问题');
      }
    } else {
      alert(errMessage);
    }
  } catch (error) {
    console.error('获取密保问题失败', error);
    alert('获取密保问题失败，请稍后再试。');
  }
};

const checkPasswordSecurity = (event) => {
  event.preventDefault();
  if (userAnswer.value === securityAnswer.value) {
    showPasswordReset.value = true;
    showEmailChecking.value = null;
  } else {
    alert("答案错误");
  }
};

const validateEmail = (email) => {
  return emailRegex.test(email);
};
</script>